<?php

namespace App\Http\Controllers\home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class ShopcartController extends Controller
{
    /**
     *  购物车
     */
    public function getIndex()
    {
        // 查询登陆者的ID
        $uid = DB::table('user') -> where('username','=',session('homeusername')) -> select('id') -> first();

        // 查询登录用户的购物车数据
        $arr1 = DB::table('shopcart') -> where('uid','=',$uid['id']) -> get();

        // 查询商品表
        $arr2 = DB::table('goods_basis') -> get();
        $data = [];
        foreach ($arr1 as $k => $v) {
            foreach ($arr2 as $kk => $vv) {
                if ($v['gid'] == $vv['id']) {
                    $data[] = array_merge($vv,$v);
                }
            }
        }
        
        // 查询总条数
        $num = DB::table('shopcart') -> where('uid','=',$uid['id']) -> count();
        
        // 加载模板 并传数据
        return view('home.detail.shopcart',['data'=>$data,'num'=>$num]);

    }

    /**
    *   删除购物车中的商品
    */
    public function getDelete(Request $request)
    {
        // 接受要删除的ID
        $id = $request -> input('id');

        // 删除数据表里的信息
        $res = DB::table('shopcart') -> where('id','=',$id) -> delete();

        if ($res) {
            return redirect('/home/shopcart');
        } else {
            return back();
        }
    }

    /**
    *   购物车结算
    */
    public function getSettlement1(request $request)
    {
        $id = $request -> all();

        if ($id) {
            $arr = DB::table('user') -> where('username','=',session('homeusername')) -> first();
            DB::table('shopcart') -> where('uid','=',$arr['id']) -> update(['status'=>0]);

        }
        foreach ($id as $k=>$v) {

            DB::table('shopcart') -> where('id','=',$k) -> update(['count'=>$v,'status'=>1]);
        }
        return $k;
    }
}
